<template>
  <el-dialog
    :custom-class="'publish-dialog'"
    @close="close"
    title="发布成功"
    v-model="isVisible"
    append-to-body
    width="700px"
  >
    <el-row>
      <el-col :span="8">
        <p>封面图</p>
        <img class="cover" :src="pageData.coverImg" />
      </el-col>
      <el-col :span="16">
        <div class="flex">
          <img
            class="share"
            :src="
              (pageData.setting && pageData.setting.shareImg) ||
              `http://${localIp}:7878/upload/LOGO.png`
            "
          />

          <div class="ml-2">
            <h4 class="title">{{ pageData.title }}</h4>
            <h4>{{ pageData.desc }}</h4>
          </div>
        </div>
        <div>
          <el-tabs v-model="activeName">
            <el-tab-pane label="发布为作品" name="works"></el-tab-pane>
            <el-tab-pane label="发布为模版" name="template"></el-tab-pane>
          </el-tabs>

          <div v-show="activeName === 'works'">
            <div class="flex">
              <el-input
                class="flex-1 mr-2"
                v-model.trim="channelName"
                placeholder="请输入渠道名称"
              ></el-input>
              <el-button size="mini" type="primary" round @click="createChannel()">
                创建新渠道
              </el-button>
            </div>
            <div
              class="flex justify-between align-center mt-1"
              v-for="item in channels"
              :key="item.channelId"
            >
              <canvas :id="`qrcode_${item.channelId}`" class="qrcode"></canvas>
              <div class="ml-2 flex-1">
                <span class="title">{{ item.channelName }}</span>
                <el-input
                  class="mt-1"
                  :id="`channel-url-${item.channelId}`"
                  :model-value="item.url"
                >
                </el-input>
              </div>
              <div class="flex flex-column ml-1">
                <el-button
                  :disabled="channels.length === 1"
                  class="m-0"
                  size="mini"
                  type="danger"
                  round
                  :loading="channelLoading"
                  @click="delChannel(item.channelId)"
                >
                  删除渠道
                </el-button>
                <el-button
                  :id="`copy_button_${item.channelId}`"
                  :data-clipboard-target="`#channel-url-${item.channelId}`"
                  class="m-0 mt-1"
                  size="mini"
                  round
                >
                  复制
                </el-button>
              </div>
            </div>
          </div>
          <template v-if="channels.length > 0">
            <div v-show="activeName !== 'works'">
              <div class="flex justify-between align-center mt-1">
                <canvas id="qrcode_template" class="qrcode"></canvas>
                <div class="ml-2 flex-1">
                  <span class="title">模版信息</span>
                  <div class="flex">
                    <el-input
                      class="mt-1 mr-1"
                      id="channel-url-template"
                      :model-value="channels[0].url"
                    >
                    </el-input>
                    <el-button
                      id="copy_button_template"
                      data-clipboard-target="#channel-url-template"
                      class="mt-1"
                      size="mini"
                      round
                    >
                      复制
                    </el-button>
                  </div>
                </div>
              </div>
              <div class="flex justify-center">
                <el-button
                  :loading="templateLoading"
                  type="primary"
                  round
                  @click="publishTemplate()"
                >
                  发布模版
                </el-button>
              </div>
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script lang="ts">
import { defineComponent, ref, watch, computed, nextTick } from "vue";
import { useStore } from "vuex";
import { IGlobalDataProps } from "@/store/index.ts";
import { IPageProps } from "@/store/modules/editor.ts";
import { uuid } from "@/utils/index.ts";
import QRCode from "qrcode";
import ClipboardJS from "clipboard";
import useAppInstance from "@/hooks/useAppInstance";
import {
  getworksChannelsApi,
  worksChannelApi,
  deleteWorksChannelApi,
} from "@/api/common.api";
import { fail } from "assert";
export default defineComponent({
  props: {
    modelValue: {
      type: Boolean,
      default: false,
    },
  },
  setup(props, context) {
    const store = useStore<IGlobalDataProps>();
    const { globalFunc } = useAppInstance();
    let clipboards: any = []; // ClipboardJS实例用于卸载
    let isVisible = ref(false);
    let channelLoading = ref(false);
    let templateLoading = ref(false);
    let createChannelLoading = ref(false);

    let activeName = ref("works");
    let channelName = ref("");
    let localIp = ref(window["localIp"]);
    let pageData = computed<IPageProps>(() => store.state.editor.page);
    let channels = ref<any>([]);
    let close = () => {
      context.emit("update:modelValue", false);
    };

    // 获取渠道信息
    let getworksChannels = async () => {
      channels.value = await getworksChannelsApi();
    };

    // 生成二维码
    let generateQRCode = (channelId: string, url: string) => {
      let el = document.getElementById(`qrcode_${channelId}`) as HTMLCanvasElement;
      QRCode.toCanvas(el, url, {
        width: 90,
      });
    };
    // 删除渠道
    let delChannel = async (channelId: string) => {
      try {
        channelLoading.value = true;
        await deleteWorksChannelApi(channelId);
        getworksChannels();
      } catch (error) {
      } finally {
        channelLoading.value = false;
      }
    };
    // 创建新渠道
    let createChannel = async () => {
      if (!channelName.value) {
        return globalFunc.$message.warning({
          message: "渠道名称不能为空",
          type: "warning",
        });
      }
      try {
        createChannelLoading.value = true;
        await worksChannelApi({ channelName });
        getworksChannels();
        channelName.value = "";
      } catch (error) {
      } finally {
        createChannelLoading.value = false;
      }
    };

    // 发布为模版
    let publishTemplate = () => {
      templateLoading.value = true;
      setTimeout(() => {
        templateLoading.value = false;
        globalFunc.$message.success({
          message: "发布模版成功",
          type: "success",
        });
      }, 3000);
    };

    // 监听对象数组,指向同一个引入地址,取到的新旧值一样的
    watch(
      () => [...channels.value],
      (newChannels: any, oldChannels: any) => {
        // 判断是否新增
        if (newChannels.length > oldChannels.length) {
          let { channelId, url } = newChannels[newChannels.length - 1];
          generateQRCode(channelId, url);
          clipboardHandler(channelId);
        }
      },
      {
        flush: "post",
      }
    );

    // 是否展示
    watch(
      () => props.modelValue,
      async (newVal: boolean) => {
        isVisible.value = newVal;
        if (newVal) {
          await getworksChannels();
          await nextTick();
          channels.value.forEach((item: any) => {
            let { channelId, url } = item;
            generateQRCode(channelId, url);
            clipboardHandler(channelId);
          });
          generateQRCode(
            "template",
            `http://${localIp.value}:8089/#/?channelId=${uuid()}`
          );
          clipboardHandler("template");
        } else {
          // 卸载
          clipboards.forEach((clipboard: any) => clipboard.destroy());
          clipboards = [];
        }
      }
    );

    // 复制
    let clipboardHandler = async (id: string) => {
      await nextTick();
      let copy = document.getElementById(`copy_button_${id}`) as HTMLElement;
      const clipboard = new ClipboardJS(copy);
      clipboards.push(clipboard);
      clipboard.on("success", (e) => {
        globalFunc.$message.success({
          message: "复制成功",
          type: "success",
        });
        e.clearSelection();
      });
      clipboard.on("error", (e) => {
        globalFunc.$message.warning({
          message: "复制失败",
          type: "warning",
        });
      });
    };

    return {
      isVisible,
      close,
      activeName,
      channelName,
      pageData,
      channels,
      delChannel,
      channelLoading,
      templateLoading,
      createChannelLoading,
      createChannel,
      publishTemplate,
      localIp,
    };
  },
});
</script>
<style lang="scss" scoped>
.cover {
  width: 170px;
  max-height: 333px;
  border: 1px #cccccc dashed;
}
.share,
.qrcode {
  width: 90px;
  height: 90px;
  border: 1px #dddddd solid;
  border-radius: 10px;
}

.title {
  font-weight: bold;
  color: #000;
}
</style>
<style lang="scss">
.publish-dialog {
  .el-dialog__header {
    border-bottom: 1px solid #eeeeee;
  }
}
</style>
